<?php

namespace App\Http\Middleware;

use App\Consts\ExceptionCode;
use App\Consts\GlobalLoginConst;
use App\Consts\GlobalResultCode;
use App\Exceptions\Error;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;

class VerifyParamsEncrypt
{
    /**
     * Handle an incoming request.
     * 校验参数加密签名
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        return $next($request);

        // 获取所有参数
        $bodyForm = $request->all();

        // 验证客户端参数中是否含有timestamp和sign
        if (empty($bodyForm['timestamp']) || empty($bodyForm['sign'])) {
            return Error::handle(lang('Login error'), ExceptionCode::LOGIN_FAIL, GlobalResultCode::SIGN_PLATFORM_ERROR);
        }

        // 验证客户端时间和服务器时间是否 > 30s
        if (time() - (int)$bodyForm['timestamp'] > 30) {
            return Error::handle(lang('Login error'), ExceptionCode::LOGIN_FAIL, GlobalResultCode::SIGN_TIME_OVER);
        }

        $sign = $bodyForm['sign'];

        // 去掉参数中的sign
        Arr::forget($bodyForm, 'sign');

        // 签名不验证 file
        if (isset($bodyForm['file'])) {
            unset($bodyForm['file']);
        }

        // 按ASCII码升序排序
        ksort($bodyForm);

        // 将其他参数进行加密
        $raw = '';
        foreach ($bodyForm as $key => $value) {
            $raw .= $key . '-' . $value . '--';
        }
        // 首位拼接，各个端的secret（随机字符串）
        $webSecret = GlobalLoginConst::$tokenEncrypt[GlobalLoginConst::LOGIN_PLATFORM_WEB]['signSecret'];
        $raw = $webSecret . $raw . $webSecret;

        // 加密字符串去掉 换行符 和 空格
        $raw = str_replace([PHP_EOL, ' '], '', $raw);

        if (md5($raw) !== $sign) {
            return Error::handle(lang('Login error'), ExceptionCode::LOGIN_FAIL, GlobalResultCode::SIGN_VERIFY_FAIL);
        }

        return $next($request);
    }
}

